// permission-info.js
import { MenuData } from './menuData';
import { FunctionPermissionDefinition } from '../platform/functionPermissionDefinition';
import { FunctionPermissionSimpleData } from '../platform/functionPermissionSimpleData';
import { Definition } from '../common/definition';
import { TestConfig } from '../common/testConfig';

export class PermissionInfo {
  constructor() {
    /** @type {MenuData[]} 菜单树 */
    this.menuTree = [];

    /** @type {Object.<string, any>} 权限映射表（私有） */
    this._functionMenuPermissionMap = {};

    /** @type {Object.<string, string>} 编码名称映射 */
    this.codeNameMap = {};

    /** @type {MenuData[]} 可显示菜单缓存（私有） */
    this._showAbleMenuTree = [];
    this._router = [];

    /*
    // todo 临时path map, 后期通过后台配置的权限更新
    this.tmpPathMap = {
      'M_BasicData': 'basicData',
      'M_Set_CommodityMgr': 'commodityMgt',
      'M_Set_CommodityMgr_Category': 'category',
      'M_Set_CommodityMgr_Data': 'commodities',
      'M_Set_CommodityMgr_Attribute': 'units',
      'CommodityDetailPage': 'commodity',

      'M_Sales': 'sales',
      'M_Sales_Sales': 'sales',
      'M_Sales_Sales_Quotation': 'salesQuotation',
      'M_Sales_Sales_Contract': 'salesOrders',
      'M_Sales_Sales_Return': 'salesReturnOrders',
      'M_Retail': 'retails',
      'M_Retail_Cashier': 'retail',
      'M_Retail_Records': 'retailRecords',
      'SalesDetailPage': 'order',
      'M_SALES_Metal_Contract': "metalSaleContracts",
      'MetalSalesDetailPage': 'metalSaleOrder',

      'M_Purchase': 'purchase',
      'M_Purchase_Purchase': 'purchase',
      'M_Purchase_Purchase_Contract': 'purchaseOrders',
      'M_Purchase_Purchase_Return': 'purchaseReturnOrders',
      'M_Purchase_Supplier': 'supplier',  // todo 这里不知为何被跳过，暂时不处理
      'M_Purchase_Supplier_Mgr': 'suppliers',
      'SupplierDetailPage': 'supplier',
      'PurchaseDetailPage': 'purchaseOrder',
      'M_Purchase_Metal_Contract': "metalContracts",
      'MetalPurchaseDetailPage': 'metalOrder',
      'M_Purchase_Metal_Contract_Commodities': "metalpurchasecommodities",
      'M_SALES_Metal_Contract_Commodities': "metalsalescommodities",


      'M_Inventory': 'inventory',
      'M_Inventory_Doc': 'inventorydoc',
      'M_InventoryInMgt': 'inOrders',
      'M_InventoryOutMgt': 'outOrders',
      'M_Inventory_Doc_Check': 'check',
      'M_Inventory_Doc_Allocate': 'allocate',
      'M_Inventory_Doc_Assembler': 'assemblers',
      'M_Inventory_Mgr': 'inventoryMgt',
      'M_Inventory_Mgr_Inquiry': 'inquiry',
      'M_Inventory_Mgr_InOutRecord': 'inoutrecords',
      'M_Inventory_Mgr_Wares': 'warehouses',
      'WarehouseDetailPage': 'warehouse',
      'M_Inventory_Types': 'inventorytypes',
      'InventoryDetailPage': 'inventory',
      'InventoryAssemblerDetailPage': 'assembler',
      'InventorySheetDetailPage': 'sheet',

      'M_Customer': 'customer',
      'M_Customer_Mgr': 'customersMgt',
      'M_Customer_Mgr_Info': 'customers',
      'CustomerDetailPage': 'customer',


      'M_Fund': 'fund',
      'M_Fund_Account_DealingReceive': 'dealingReceive',
      'M_Fund_Account_Receivable': 'receivable',
      'M_Fund_Account_Receipts': 'receipts',
      'M_Fund_Account_PreReceive': 'prereceive',
      'M_Fund_Account_OtherReceive': 'otherreceive',
      'M_Fund_Account_Dealing_Payment': 'dealingPayment',
      'M_Fund_Account_Payable': 'payable',
      'M_Fund_Account_Payment': 'payment',
      'M_Fund_Account_PrePayment': 'prepayment',
      'M_Fund_Account_OtherPayment': 'otherpayment',
      'M_Fund_Account_PaymentRefund': 'paymentrefund',
      'M_Fund_Fund': "fundorder",
      'M_Fund_Fund_Income': 'income',
      'M_Fund_Fund_Expenditure': 'expenditure',
      'ReceiptOrderDetailPage': 'receiptorder',
      'PaymentOrderDetailPage': 'paymentorder',

      'M_Fund_Account': 'fundaccount',
      'M_Fund_StatementMgt': 'statemgt',
      'M_Fund_Fund_Account': 'fundacounts',
      'M_Fund_Fund_AccountMgt': 'fundaccountmgt',
      'M_Fund_Metal_FundType': 'metalFundType',
      'M_Fund_FundType': 'fundtype',
      'M_Fund_Fund_IncomeType': 'incometype',
      'M_Fund_Fund_ExpenditureType': 'expendituretype',
      'M_Fund_Fund_OtherFeeType': 'otherfeetype',



      'M_Purchase_Sales': 'business',
      'M_Supplier_Customer': 'partners',
      'PendingPaymentOrderDetailPage': 'pendingPaymentOrder',
      'PendingReceiptOrderDetailPage': 'pendingReceiptOrder',
      'M_Metal_Refining': 'refinings',
      'MetalRefiningOrderDetailPage': 'refiningOrder',
    }
    this.tmpMenuNameMap = {
      'M_BasicData': '基础资料',
      'M_Set_CommodityMgr': '商品信息',
      'M_Set_CommodityMgr_Category': '商品类别',
      'M_Set_CommodityMgr_Data': '商品信息',
      'M_Set_CommodityMgr_Attribute': '计量单位',
      'CommodityDetailPage': '商品详情',

      'M_Sales': '销售',
      'M_Sales_Sales': '销售单据',
      'M_Sales_Sales_Quotation': '报价单',
      'M_Sales_Sales_Contract': '销售单',
      'M_Sales_Sales_Return': '销售退货单',
      'M_Retail': '零售',
      'M_Retail_Cashier': '零售收银',
      'M_Retail_Records': '收银记录',
      'SalesDetailPage': '销售单详情',
      'M_SALES_Metal_Contract': "板料销售单",
      'MetalSalesDetailPage': '板料销售单详情',

      'M_Purchase': '采购',
      'M_Purchase_Purchase': '采购单据',
      'M_Purchase_Purchase_Contract': '采购单',
      'M_Purchase_Purchase_Return': '采购退货单',
      'M_Purchase_Supplier': '供应商管理',
      'M_Purchase_Supplier_Mgr': '供应商',
      'PurchaseDetailPage': '采购单详情',
      'M_Purchase_Metal_Contract': "回购入库单",
      'MetalPurchaseDetailPage': '回购入库单详情',
      'M_Purchase_Metal_Contract_Commodities': "回购入库明细",
      'M_SALES_Metal_Contract_Commodities': "板料出库明细",


      'M_Inventory': '库存',
      'M_Inventory_Doc': '库存单据',
      'M_InventoryInMgt': '入库管理',
      'M_InventoryOutMgt': '出库管理',
      'M_Inventory_Doc_Check': '盘点单',
      'M_Inventory_Doc_Allocate': '调拨单',
      'M_Inventory_Doc_Assembler': '盘点分类',//'组装拆卸单',

      'M_Inventory_Mgr': '库存管理',
      'M_Inventory_Mgr_Inquiry': '库存查询',
      'M_Inventory_Mgr_InOutRecord': '出入库明细',
      'M_Inventory_Mgr_Wares': '仓库管理',
      'WarehouseDetailPage': '仓库详情',
      'M_Inventory_Types': '出入库类型',
      'InventoryDetailPage': '单据详情',
      'InventoryAssemblerDetailPage': '盘点分类详情',//'组装拆卸详情',
      'InventorySheetDetailPage': '盘点详情',

      'M_Customer': '客户',
      'M_Customer_Mgr': '客户管理',
      'M_Customer_Mgr_Info': '客户信息',
      'CustomerDetailPage': '客户详情',

      'M_Fund': '资金',
      'M_Fund_Account_DealingReceive': '往来收款',
      'M_Fund_Account_Receivable': '应收款',
      'M_Fund_Account_Receipts': '收款单',
      'M_Fund_Account_PreReceive': '预收款',
      'M_Fund_Account_OtherReceive': '其他收款',
      'M_Fund_Account_ReceiveRefund': '收款退费',
      'M_Fund_Account_Dealing_Payment': '往来付款',
      'M_Fund_Account_Payable': '应付款',
      'M_Fund_Account_Payment': '付款单',
      'M_Fund_Account_PrePayment': '预付款',
      'M_Fund_Account_OtherPayment': '其他付款',
      'M_Fund_Account_PaymentRefund': '付款退款',
      'M_Fund_Fund': "资金单据",
      'M_Fund_Fund_Income': '收入',
      'M_Fund_Fund_Expenditure': '支出',
      'ReceiptOrderDetailPage': '收款单详情',
      'PaymentOrderDetailPage': '付款单详情',

      'M_Fund_StatementMgt': '对账',
      'M_Fund_Fund_Account': '资金账户',
      'M_Fund_Fund_AccountMgt': '账户管理',
      'M_Fund_Metal_FundType': '贵金属账户类型',
      'M_Fund_FundType': '资金类型',
      'M_Fund_Fund_IncomeType': '收入类型',
      'M_Fund_Fund_ExpenditureType': '支出类型',
      'M_Fund_Fund_OtherFeeType': '往来费用类型',

      'SupplierDetailPage': '供应商详情',
      'PendingPaymentOrderDetailPage': '应付单详情',
      'PendingReceiptOrderDetailPage': '应收单详情',
      'M_Metal_Refining': '加工单',
      'MetalRefiningOrderDetailPage': '加工单详情',
    }
    this.tmpComponentMap = {
      'M_BasicData': 'Layout',
      'M_Set_CommodityMgr_Attribute': 'basicData/commodityMgt/unitsPage',
      'M_Set_CommodityMgr_Category': 'basicData/commodityMgt/categoriesPage',
      'M_Set_CommodityMgr_Data': 'basicData/commodityMgt/commoditiesPage',
      'CommodityDetailPage': 'commodity/commodityDetailPage',

      'M_Sales': 'Layout',
      'M_Sales_Sales_Contract': 'sales/salesMgtPage',
      'SalesDetailPage': 'sales/salesDetailPage',
      'M_SALES_Metal_Contract': "sales/metalSalesContractMgtPage",
      'MetalSalesDetailPage': 'sales/metalSalesDetailPage',
      'M_SALES_Metal_Contract_Commodities': "sales/metalSalesContractCommoditiesPage",

      'M_Purchase': 'Layout',
      'M_Purchase_Purchase_Contract': 'purchase/purchaseMgtPage',
      'PurchaseDetailPage': 'purchase/purchaseDetailPage',
      'M_Purchase_Supplier_Mgr': 'partner/suppliersPage',
      'SupplierDetailPage': 'partner/supplierDetailPage',
      'M_Purchase_Metal_Contract': "purchase/metalPurchaseContractMgtPage",
      'MetalPurchaseDetailPage': 'purchase/metalPurchaseDetailPage',
      'M_Purchase_Metal_Contract_Commodities': "purchase/metalPurchaseContractCommoditiesPage",


      'M_Inventory': 'Layout',
      'M_Inventory_Mgr_Wares': 'inventory/warehousesPage',
      'WarehouseDetailPage': 'inventory/warehouseDetailPage',
      'M_Inventory_Types': 'inventory/inventoryTypesPage',
      'M_InventoryInMgt': 'inventory/inventoryBatchMgrPage',
      'M_InventoryOutMgt': 'inventory/inventoryBatchMgrPage',
      'InventoryDetailPage': 'inventory/inventoryDetailPage',
      'M_Inventory_Mgr_Inquiry': 'inventory/subcommodityInventorySumPage',
      'M_Inventory_Mgr_InOutRecord': 'inventory/subcommodityInoutRecordsPage',
      'M_Inventory_Doc_Assembler': 'inventory/inventoryAssemblerMgrPage',
      'InventoryAssemblerDetailPage': 'inventory/inventoryAssemblerDetailPage',
      'M_Inventory_Doc_Check': 'inventory/inventorySheetMgrPage',
      'InventorySheetDetailPage': 'inventory/inventorySheetDetailPage',

      'M_Customer': 'Layout',
      'M_Customer_Mgr_Info': 'partner/customersPage',
      'CustomerDetailPage': 'partner/customerDetailPage',

      'M_Fund': 'Layout',
      'M_Fund_Account_Receipts': 'fund/receiptMgtPage',
      'ReceiptOrderDetailPage': 'fund/receiptOrderDetailPage',
      'M_Fund_Account_Payment': 'fund/paymentMgtPage',
      'PaymentOrderDetailPage': 'fund/paymentOrderDetailPage',
      "M_Fund_Metal_FundType": 'fund/selfFundAccountTypesPage',
      'M_Fund_Fund_Account': 'fund/fundAccountMgtPage',
      'M_Fund_Fund_OtherFeeType': 'fund/otherFeeTypeMgtPage',



      'M_Purchase_Sales': 'Layout',
      'M_Supplier_Customer': 'Layout',
      'M_Fund_Account_Payable': 'fund/payableMgtPage',
      'M_Fund_Account_Receivable': 'fund/receivableMgtPage',
      'PendingPaymentOrderDetailPage': 'fund/pendingPaymentOrderDetailPage',
      'PendingReceiptOrderDetailPage': 'fund/pendingReceiptOrderDetailPage',
      'M_Metal_Refining': 'manufactor/metalRefiningContractMgtPage',
      'MetalRefiningOrderDetailPage': 'manufactor/metalRefiningOrderDetailPage',

    },

      this.queryParamMap = {
        'M_InventoryInMgt': { 'type': 'in' },
        'M_InventoryOutMgt': { 'type': 'out' },
      }
      */

  }

  /**
   * 克隆构造函数
   * @param {PermissionInfo} cloneData - 要克隆的源数据
   * @returns {PermissionInfo} 新实例
   */
  static clone(cloneData) {
    const instance = new PermissionInfo();
    // 深拷贝菜单树
    instance.menuTree = cloneData.menuTree.map(item => MenuData.clone(item));
    instance.initFunctionMenuPermissionMap();
    instance.codeNameMap = { ...cloneData.codeNameMap };
    return instance;
  }

  /**
   * 从JSON创建实例
   * @param {Object} json - 原始JSON数据
   * @returns {PermissionInfo} 新实例
   */
  static fromJson(json) {

   // console.log('PermissionInfo.fromJson', json);

    const instance = new PermissionInfo();

    // 解析菜单树
    if (json.menuTree && Array.isArray(json.menuTree)) {
      instance.menuTree = json.menuTree.map(item => MenuData.fromJson(item));
      instance.initFunctionMenuPermissionMap();
    }

    // 解析权限数据
    if (json.permissions && Array.isArray(json.permissions)) {
      json.permissions.forEach(element => {
        const key = Object.keys(element)[0];
        if (key) instance.codeNameMap[key] = element[key];
      });
    }

    // 移动端特殊处理
    if (Definition.isMobileMode) {
      this._processMobileMenus(instance);
    }

    // 生成编码映射
    instance.menuTree.forEach(item => item.getCodeNameMap(instance.codeNameMap));

    return instance;
  }

  /** 初始化权限映射表 */
  initFunctionMenuPermissionMap() {
    this._functionMenuPermissionMap = {};
    this.menuTree.forEach(item =>
      item.initFunctionMenuPermissionMap(this._functionMenuPermissionMap)
    );
  }

  /**
   * 获取可显示菜单树
   * routerMenu = true 会补齐详情等没有菜单栏的页面
   * @param {boolean} [excludePhoneMenu=false] 是否排除手机菜单
   * @returns {MenuData[]}
   */
  getMenuShowableMenuTree(excludePhoneMenu = false, routerMenu = false) {
    if (!routerMenu) {

      if (this._showAbleMenuTree.length > 0) {
        return this._showAbleMenuTree
      }           
      const filterMenuTree = (menuList) => {
        return menuList
          .filter(item => !item.excludeMenuTree && 
            // 添加隐藏菜单，调试使用
            (!item.hideInMenu && !TestConfig.simShowHideMenuForTest)
            &&
            !(excludePhoneMenu && item.excludePhoneMenu))
          .map(item => {
            const clonedItem = MenuData.clone(item);
            if (clonedItem.subMenuList && clonedItem.subMenuList.length > 0) {
              clonedItem.subMenuList = filterMenuTree(clonedItem.subMenuList);
            }
            return clonedItem;
          });
      };

      this._showAbleMenuTree = filterMenuTree(this.menuTree);



      return this._showAbleMenuTree;
    }

    if (routerMenu) {
      if (this._router.length > 0) {
        return this._router
      }

      const filterRouterTree = (menuList) => {
        return menuList
          .filter(item => !item.excludeMenuTree &&
            !(excludePhoneMenu && item.excludePhoneMenu))
          .map(item => {
            const clonedItem = MenuData.clone(item);
            if (clonedItem.subMenuList && clonedItem.subMenuList.length > 0) {
              clonedItem.subMenuList = filterRouterTree(clonedItem.subMenuList);
            }
            return clonedItem;
          });
      };

      this._router = filterRouterTree(this.menuTree);

      return this._router;
    }
  }


  /**
   * 获取获取左侧菜单树json 对象
   * @param {boolean} [excludePhoneMenu=false] 是否排除手机菜单
   * routerMenu = true 会补齐详情等没有菜单栏的页面
   * @returns {MenuData[]}
   */
  /*
  getLeftSiderbarMenuTree_drop(excludePhoneMenu = false, routerMenu = false) {
    const convertMenuToSidebarItem = (menu, isFirstLevel = false) => {

      const item = {
        name: menu.path || ((isFirstLevel ? "/" : "") + (this.tmpPathMap[menu.code] || `/${menu.code}`)),
        path: menu.path || ((isFirstLevel ? "/" : "") + (this.tmpPathMap[menu.code] || `/${menu.code}`)),  // todo        
        component: this.tmpComponentMap[menu.code],
        // Add alwaysShow for first-level menus
        ...(isFirstLevel && { alwaysShow: true }),
        // 检查是否有查询参数并添加
        ...(this.queryParamMap[menu.code] && { query: JSON.stringify(this.queryParamMap[menu.code]) }),
        meta: {
          title: this.tmpMenuNameMap[menu.code] || menu.name,
          icon: menu.icon || 'tab',
          noCache: false,
          link: null
        }
      };



      if (menu.subMenuList && menu.subMenuList.length > 0) {
        item.redirect = "noRedirect";
        item.children = menu.subMenuList
          .filter(subMenu => !subMenu.excludeMenuTree &&
            !(excludePhoneMenu && subMenu.excludePhoneMenu))
          .map(subMenu => convertMenuToSidebarItem(subMenu));
      }

      return item;
    };

    let ret = this.getMenuShowableMenuTree(excludePhoneMenu, routerMenu)
      .filter(menu => !menu.excludeMenuTree)
      .map(menu => convertMenuToSidebarItem(menu, true)); // Pass true for first-level menus

    console.log("getLeftSiderbarMenuTree routerMenu:" + routerMenu + " ;value:", ret);

    return ret;
  }
  */

  /**
   * 获取获取左侧菜单树json 对象
   * @param {boolean} [excludePhoneMenu=false] 是否排除手机菜单
   * routerMenu = true 会补齐详情等没有菜单栏的页面
   * @returns {MenuData[]}
   */
  getLeftSiderbarMenuTree(excludePhoneMenu = false, routerMenu = false) {
    const convertMenuToSidebarItem = (menu) => {

      // 注意本处采用如下方式，component 参数才会正常处理，不然 component 参数无效
      // 具体原因目前不太清楚
      const item = {
        ...menu.webRouteInfo,
      }


      if (menu.subMenuList && menu.subMenuList.length > 0) {
        item.children = menu.subMenuList
          .filter(subMenu => !subMenu.excludeMenuTree &&
            !(excludePhoneMenu && subMenu.excludePhoneMenu))
          .map(subMenu => convertMenuToSidebarItem(subMenu));
      }

      //console.log('convertMenuToSidebarItem menu:',  menu);    
      //console.log('convertMenuToSidebarItem item:', item);      

      return item;
    };

    let ret = this.getMenuShowableMenuTree(excludePhoneMenu, routerMenu)
      .filter(menu => !menu.excludeMenuTree)
      .map(menu => convertMenuToSidebarItem(menu)); // Pass true for first-level menus

    console.log("getLeftSiderbarMenuTree routerMenu:" + routerMenu + " ;value:", ret);

    return ret;
  }


  /**
   * 检查权限
   * @param {string[]} permissionCodeList 权限代码列表
   * @returns {boolean}
   */
  hasPermission(permissionCodeList) {
    return permissionCodeList.some(code =>
      code && this._functionMenuPermissionMap.hasOwnProperty(code)
    );
  }

  /**
   * 获取所有叶子节点编码
   * @returns {string[]}
   */
  getLeafTreeNode() {
    const nodeList = [];
    const collectLeafCodes = (menu) => {
      if (menu.subMenuList && menu.subMenuList.length > 0) {
        menu.subMenuList.forEach(collectLeafCodes);
      } else {
        nodeList.push(menu.code);
      }
    };
    this.menuTree.forEach(collectLeafCodes);
    return nodeList;
  }

  /**
   * 处理移动端菜单（私有静态方法）
   * @param {PermissionInfo} instance - 当前实例
   */
  static _processMobileMenus(instance) {
    let customerMenuData, salesMenuData, statementMenuData,
      purchaseMenuData, fundMenuData, fundRootMenuData;

    const checkMenu = (element) => {
      if (element.excludeShortcut || element.excludePhoneMenu) return;

      switch (element.code) {
        case FunctionPermissionDefinition.M_Customer:
          customerMenuData = element; break;
        case FunctionPermissionDefinition.M_Sales_Sales:
          salesMenuData = element; break;
        case FunctionPermissionDefinition.M_Fund_StatementMgt:
          statementMenuData = element; break;
        case FunctionPermissionDefinition.M_Purchase_Purchase:
          purchaseMenuData = element; break;
        case FunctionPermissionDefinition.M_Fund_Fund:
          fundMenuData = element; break;
        case FunctionPermissionDefinition.M_Fund:
          fundRootMenuData = element; break;
      }
    };

    for (let element of instance.menuTree) {
      checkMenu(element);
      for (let item of element.subMenuList || []) {
        checkMenu(item);
        for (let subItem of item.subMenuList || []) {
          checkMenu(subItem);
        }
      }
    }
    // // 特殊处理 purchaseMenuData 整合单
    /*
    // 处理销售相关菜单
    if (salesMenuData) {
      const hasSalesRelated = salesMenuData.subMenuList.some(item =>
        [FunctionPermissionDefinition.M_Sales_Sales_Contract,
        FunctionPermissionDefinition.M_Sales_Sales_Return].includes(item.code)
      );
      if (hasSalesRelated) {
        salesMenuData.subMenuList.push(MenuData.fromJson(
          FunctionPermissionSimpleData.salesRelatedMenu()
        ));
      }
    }


    if (purchaseMenuData) {
      const hasPurchaseRelated = purchaseMenuData.subMenuList.some(item =>
        [FunctionPermissionDefinition.M_Purchase_Purchase_Contract,
        FunctionPermissionDefinition.M_Purchase_Purchase_Return].includes(item.code)
      );
      if (hasPurchaseRelated) {
        purchaseMenuData.subMenuList.push(MenuData.fromJson(
          FunctionPermissionSimpleData.purchaseRelatedMenu()
        ));
      }
    }
      */

    // 往来收款处理
    /*
    if (fundMenuData) {
      const hasDealingReceipt = fundMenuData.subMenuList.some(item =>
        item.code === FunctionPermissionDefinition.M_Fund_Account_Receipts
      );
      if (hasDealingReceipt) {
        fundMenuData.subMenuList.push(MenuData.fromJson(
          FunctionPermissionSimpleData.dealingPaymentReceipt()
        ));
      }

      // 日常收支处理
      const hasDirectFund = fundMenuData.subMenuList.some(item =>
        [FunctionPermissionDefinition.M_Fund_Fund_Income,
        FunctionPermissionDefinition.M_Fund_Fund_Expenditure].includes(item.code)
      );
      if (hasDirectFund) {
        fundMenuData.subMenuList.push(MenuData.fromJson(
          FunctionPermissionSimpleData.directFundInout()
        ));
      }
    }
      */

    // 特殊处理1 过滤客户菜单，客户菜单合并到销售中
    // 如果时销售菜单，又有客户菜单，并且合并和销售菜单中
    /*
  if (customerMenuData && salesMenuData && customerMenuData.subMenuList.length > 0) {
    const customerMgt = customerMenuData.subMenuList.find(
      item => item.code === FunctionPermissionDefinition.M_Customer_Mgr
    );
    if (customerMgt && customerMgt.subMenuList && customerMgt.subMenuList.length > 0) {
      const firstCode = customerMgt.subMenuList[0].code;
      const exists = salesMenuData.subMenuList.some(
        item => item.code === firstCode
      );
      if (!exists) {
        salesMenuData.subMenuList.unshift(...customerMgt.subMenuList);
      }
    }
    instance.menuTree = instance.menuTree.filter(item => item !== customerMenuData);
  }
  */

    // 对账菜单处理
    /*
    if (statementMenuData) {
      // 添加整合菜单
      statementMenuData.subMenuList.unshift(MenuData.fromJson(
        FunctionPermissionSimpleData.statement()
      ));

      if (fundRootMenuData) {
        // 移除后再插入到首位
        fundRootMenuData.subMenuList = fundRootMenuData.subMenuList.filter(item => item !== statementMenuData);
        fundRootMenuData.subMenuList.unshift(statementMenuData);
      }
    }
      */
  }

  /**
   * 转换为JSON格式
   * @returns {Object}
   */
  toJson() {
    return {
      menuTree: this.menuTree.map(item => item.toJson()),
      permissions: Object.entries(this.codeNameMap).map(([key, value]) => ({ [key]: value }))
    };
  }
}